package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goTestToMod/rate_limiter_test/utility"
	"goTestToMod/rate_limiter_test/utility/constv/errconst"
	"goTestToMod/rate_limiter_test/utility/limiter"
	"goTestToMod/rate_limiter_test/utility/resourceloader"
	"goTestToMod/rate_limiter_test/utility/response"
	"goTestToMod/rate_limiter_test/utility/systemerror"
	"net/http"
	"time"
)

func HandleError(context *gin.Context, err error, language string, bodyItem ...interface{}) {
	langType := resourceloader.GetLanguageType(language)
	systemErr, ok := err.(*systemerror.SystemError)
	if !ok {
		context.JSON(200, response.Response{Code: response.CreateFailResCode(err.Error()), Bo: bodyItem})
	} else {
		code := 200
		if systemErr.HttpCode != 0 {
			code = systemErr.HttpCode
		}
		if systemErr.ErrType == systemerror.HttpErrorType {
			context.JSON(code, response.Response{Code: response.CreateFailResCodeWithErrDetailMsg(systemErr.OriginalErr.Error(), systemErr.ErrDetailMsg), Bo: bodyItem})
			return
		}
		errValue, exist := resourceloader.GetInstance().GetErrorResource(langType, systemErr.ErrorId)
		if !exist {
			context.JSON(code, response.Response{Code: response.CreateFailResCode("errId:%s, the error no find in resource"), Bo: bodyItem})
			return
		}
		context.JSON(code, response.Response{Code: response.CreateFailResCode(fmt.Sprintf(errValue, systemErr.Parameters...)), Bo: bodyItem})
	}
	return
}

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		tpCopylimter := limiter.GetTestplanTaskLimiterInstance()
		if tpCopylimter.IsLimit() {
			taskInfos := tpCopylimter.GetTaskInfo()
			//"zh_CN"
			//"en_US"
			HandleError(c, systemerror.NewUserDefinedErrorWithCode(errconst.PlanBigTaskCopyError, http.StatusTooManyRequests, len(taskInfos), taskInfos), "en_US")
			return
		}
		go StartCopy()
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080
}

func StartCopy () {
	tpCopylimter := limiter.GetTestplanTaskLimiterInstance()
	uuid := utility.GetUuid()
	tpCopylimter.StartTask(uuid, "10260444", "testplancopy", 1000)
	defer tpCopylimter.ReleaseTask(uuid)
	time.Sleep(20 * time.Second)
}